<?php

namespace app\common\jobs;

use app\common\cache\ExportCache;
use tmcore\services\QueueService;
use tmcore\base\BaseJob;
use tmcore\traits\JobTrait;
use ReflectionClass;
use think\facade\Log;

/**
 * 异步导出
 */
class ExportJob extends BaseJob
{
    use JobTrait;

    public function doJob($data)
    {
        try {
            $params = $data['params']; //参数
            $class_name = $data['export_class_name'];
            $method_name = $data['export_method_name'];

            if(!class_exists($class_name)) return $this->error($class_name .' 类不存在');
            $reflectionClass = new ReflectionClass($class_name);
            if(!$reflectionClass->hasMethod($method_name)) return $this->error($method_name . ' 方法不存在');

            // 更新导出任务参数
            $params['export_type'] = 3;
            $params['is_async'] = 0;
            $params['file_random'] = $data['file_random'];
            $params['file_identifier'] = $data['file_identifier'];
            (new ExportCache)->setExportFile($params['file_identifier'], ['step' => 2]);
            ini_set ('memory_limit','-1');

            //异步调用方法
            call_user_func([$class_name, $method_name], $params, $data['action_info']);

            return $this->success();
        } catch (\Exception $e) {
            return $this->error('执行任务失败,' . ' 行号：' . $e->getLine() . '文件：' . $e->getFile() . '错误信息：' . $e->getMessage());
        }
    }

    public function notify($data) {
        try {
            (new QueueService)->addQueueLog($data);
        } catch (\Exception $e) {
            Log::error('执行任务失败,' . ' 行号：' . $e->getLine() . '文件：' . $e->getFile() . '错误信息：' . $e->getMessage());
        }
    }
}